<template>
	<view class="product-detail">
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 商品详情内容 -->
		<view v-else-if="product" class="detail-content">
			<!-- 商品图片轮播 -->
			<view class="image-section">
				<swiper class="product-swiper" :indicator-dots="true" :autoplay="false" :circular="true" @change="onSwiperChange">
					<swiper-item v-if="product.main_image_url">
						<image :src="product.main_image_url" class="product-image" mode="aspectFit" @click="previewImage(0)"></image>
					</swiper-item>
					<swiper-item v-for="(image, index) in product.gallery_image_urls" :key="index">
						<image :src="image" class="product-image" mode="aspectFit" @click="previewImage(index + 1)"></image>
					</swiper-item>
				</swiper>
			</view>

			<!-- 商品基本信息 -->
			<view class="info-section">
				<view class="product-title">{{ product.name }}</view>
				<view class="price-section">
					<text class="current-price">¥{{ product.price }}</text>
					<text v-if="product.market_price && product.market_price > product.price" class="market-price">¥{{ product.market_price }}</text>
				</view>
				<view class="category-info">
					<text class="category-label">分类：</text>
					<text class="category-name">{{ product.category_name }}</text>
				</view>
			</view>

			<!-- 商品描述 -->
			<view class="description-section" v-if="product.description">
				<view class="section-title">商品详情</view>
				<view class="description-content">
					<text class="description-text">{{ product.description }}</text>
				</view>
			</view>

			<!-- 推荐商品 -->
			<view class="recommend-section" v-if="recommendProducts.length > 0">
				<view class="section-title">相关推荐</view>
				<scroll-view class="recommend-scroll" scroll-x="true">
					<view class="recommend-list">
						<view class="recommend-item" v-for="item in recommendProducts" :key="item.id">
							<image :src="item.main_image_url || '/static/images/default-product.jpg'" 
								   class="recommend-image" 
								   mode="aspectFill" 
								   @click.stop="previewRecommendImage(item.main_image_url)"></image>
							<text class="recommend-name" @click="goToProduct(item.id)">{{ item.name }}</text>
							<text class="recommend-price" @click="goToProduct(item.id)">¥{{ item.price }}</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 错误状态 -->
		<view v-else class="error-container">
			<text class="error-text">商品不存在或已下架</text>
			<button class="back-btn" @click="goBack">返回</button>
		</view>

		<!-- 底部操作栏 -->
		<view v-if="product" class="bottom-actions">
			<view class="quantity-section">
				<text class="quantity-label">数量：</text>
				<view class="quantity-control">
					<button class="quantity-btn" @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
					<text class="quantity-text">{{ quantity }}</text>
					<button class="quantity-btn" @click="increaseQuantity">+</button>
				</view>
			</view>
			<button class="add-cart-btn" @click="addToCart" :disabled="adding">
				{{ adding ? '添加中...' : '加入购物车' }}
			</button>
		</view>
	</view>
</template>

<script>
import { get, showLoading, hideLoading, showError } from '@/utils/request.js'
import CartManager from '@/utils/cart.js'
import { processProductImages, processProductsImages } from '@/utils/imageUtils.js'

export default {
	data() {
		return {
			productId: null,
			product: null,
			loading: false,
			adding: false,
			quantity: 1,
			recommendProducts: [],
			currentImageIndex: 0
		}
	},
	computed: {
		// 获取所有图片URL数组
		allImageUrls() {
			if (!this.product) return [];
			
			const urls = [];
			if (this.product.main_image_url) {
				urls.push(this.product.main_image_url);
			}
			if (this.product.gallery_image_urls && this.product.gallery_image_urls.length > 0) {
				urls.push(...this.product.gallery_image_urls);
			}
			return urls;
		}
	},
	onLoad(options) {
		if (options.id) {
			this.productId = options.id;
			this.loadProductDetail();
		} else {
			uni.showToast({
				title: '商品ID无效',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
		
		// 显示分享菜单
		// #ifdef MP-WEIXIN
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		// #endif
	},
	methods: {
		// 加载商品详情
		async loadProductDetail() {
			if (!this.productId) return;

			try {
				this.loading = true;
				showLoading('加载中...');

				// 获取商品详情
				const res = await get(`/public/products/${this.productId}`);
				// 处理商品图片URL
				this.product = processProductImages(res.data);

				// 设置页面标题
				uni.setNavigationBarTitle({
					title: this.product.name
				});

				// 加载推荐商品
				await this.loadRecommendProducts();

			} catch (error) {
				console.error('加载商品详情失败:', error);
				showError('加载商品详情失败');
				this.product = null;
			} finally {
				this.loading = false;
				hideLoading();
			}
		},

		// 加载推荐商品
		async loadRecommendProducts() {
			try {
				// 获取同分类的其他商品作为推荐
				const res = await get('/public/products', {
					page: 1,
					pageSize: 6
				});
				
				// 过滤掉当前商品并处理图片URL
				const filteredProducts = (res.data.products || []).filter(item => item.id != this.productId);
				this.recommendProducts = processProductsImages(filteredProducts);
			} catch (error) {
				console.error('加载推荐商品失败:', error);
				this.recommendProducts = [];
			}
		},

		// 增加数量
		increaseQuantity() {
			this.quantity++;
		},

		// 减少数量
		decreaseQuantity() {
			if (this.quantity > 1) {
				this.quantity--;
			}
		},

		// 加入购物车
		async addToCart() {
			if (!this.product) return;

			try {
				this.adding = true;

				// 使用购物车管理工具添加商品
				if (CartManager.addToCart(this.product, this.quantity)) {
					uni.showToast({
						title: '已添加到购物车',
						icon: 'success'
					});

					// 重置数量
					this.quantity = 1;
				} else {
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				}

			} catch (error) {
				console.error('添加到购物车失败:', error);
				uni.showToast({
					title: '添加失败',
					icon: 'none'
				});
			} finally {
				this.adding = false;
			}
		},

		// 跳转到其他商品
		goToProduct(productId) {
			uni.redirectTo({
				url: `/pages/product/detail?id=${productId}`
			});
		},

		// 返回
		goBack() {
			uni.navigateBack();
		},

		// 轮播图切换事件
		onSwiperChange(event) {
			this.currentImageIndex = event.detail.current;
		},

		// 预览图片
		previewImage(index) {
			if (!this.allImageUrls || this.allImageUrls.length === 0) return;

			uni.previewImage({
				current: index,
				urls: this.allImageUrls,
				fail: (error) => {
					console.error('图片预览失败:', error);
					uni.showToast({
						title: '图片预览失败',
						icon: 'none'
					});
				}
			});
		},

		// 预览推荐商品图片
		previewRecommendImage(imageUrl) {
			if (!imageUrl) return;
			
			uni.previewImage({
				current: 0,
				urls: [imageUrl],
				fail: (error) => {
					console.error('图片预览失败:', error);
					uni.showToast({
						title: '图片预览失败',
						icon: 'none'
					});
				}
			});
		}
	},

	// 分享功能
	onShareAppMessage() {
		const product = this.product;
		if (!product) {
			return {
				title: '精美珠宝，品质之选',
				path: '/pages/discover/discover'
			}
		}

		return {
			title: `${product.name} - 精美珠宝品质之选`,
			path: `/pages/product/detail?id=${product.id}`,
			imageUrl: product.main_image_url || ''
		}
	},

	onShareTimeline() {
		const product = this.product;
		if (!product) {
			return {
				title: '精美珠宝，品质之选',
				query: ''
			}
		}

		return {
			title: `${product.name} - 精美珠宝品质之选`,
			query: `id=${product.id}`,
			imageUrl: product.main_image_url || ''
		}
	}
}
</script>

<style scoped>
.product-detail {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 160rpx; /* 增加底部空间，确保内容不被遮挡 */
}

/* 加载状态 */
.loading-container, .error-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 60vh;
}

.loading-text, .error-text {
	font-size: 28rpx;
	color: #999999;
	margin-bottom: 20rpx;
}

.back-btn {
	background-color: #D4AF37;
	color: white;
	border: none;
	border-radius: 50rpx;
	padding: 20rpx 40rpx;
	font-size: 28rpx;
}

/* 图片轮播 */
.image-section {
	background-color: white;
	margin-bottom: 20rpx;
	padding: 20rpx;
}

.product-swiper {
	width: 100%;
	height: 400rpx; /* 进一步减小高度 */
	border-radius: 10rpx;
	overflow: hidden;
	background-color: #f8f8f8;
}

.product-image {
	width: 100%;
	height: 100%;
	border-radius: 10rpx;
	cursor: pointer;
	transition: opacity 0.2s ease;
}

.product-image:active {
	opacity: 0.8;
}

/* 商品信息 */
.info-section {
	background-color: white;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.product-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
	line-height: 1.4;
}

.price-section {
	display: flex;
	align-items: baseline;
	margin-bottom: 20rpx;
}

.current-price {
	font-size: 48rpx;
	font-weight: bold;
	color: #D4AF37;
	margin-right: 20rpx;
}

.market-price {
	font-size: 28rpx;
	color: #999999;
	text-decoration: line-through;
}

.category-info {
	display: flex;
	align-items: center;
}

.category-label {
	font-size: 28rpx;
	color: #666666;
}

.category-name {
	font-size: 28rpx;
	color: #D4AF37;
	font-weight: bold;
}

/* 商品描述 */
.description-section {
	background-color: white;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
}

.description-content {
	line-height: 1.6;
	margin-bottom: 20rpx;
}

.description-text {
	font-size: 28rpx;
	color: #666666;
	word-wrap: break-word;
	white-space: pre-wrap;
}

/* 推荐商品 */
.recommend-section {
	background-color: white;
	padding: 30rpx;
}

.recommend-scroll {
	white-space: nowrap;
}

.recommend-list {
	display: flex;
	gap: 20rpx;
}

.recommend-item {
	display: inline-block;
	width: 200rpx;
	text-align: center;
}

.recommend-image {
	width: 200rpx;
	height: 200rpx;
	border-radius: 10rpx;
	margin-bottom: 10rpx;
	cursor: pointer;
	transition: opacity 0.2s ease;
}

.recommend-image:active {
	opacity: 0.8;
}

.recommend-name {
	display: block;
	font-size: 24rpx;
	color: #333333;
	margin-bottom: 5rpx;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.recommend-price {
	display: block;
	font-size: 26rpx;
	color: #D4AF37;
	font-weight: bold;
}

/* 底部操作栏 */
.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: white;
	padding: 20rpx 30rpx;
	border-top: 1rpx solid #EEEEEE;
	display: flex;
	align-items: center;
	justify-content: space-between;
	z-index: 100;
}

.quantity-section {
	display: flex;
	align-items: center;
}

.quantity-label {
	font-size: 28rpx;
	color: #333333;
	margin-right: 20rpx;
}

.quantity-control {
	display: flex;
	align-items: center;
	border: 1rpx solid #DDDDDD;
	border-radius: 10rpx;
	overflow: hidden;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	background-color: #F5F5F5;
	border: none;
	font-size: 32rpx;
	color: #333333;
	display: flex;
	align-items: center;
	justify-content: center;
}

.quantity-btn:disabled {
	color: #CCCCCC;
}

.quantity-text {
	width: 80rpx;
	height: 60rpx;
	line-height: 60rpx;
	text-align: center;
	font-size: 28rpx;
	color: #333333;
	background-color: white;
}

.add-cart-btn {
	background-color: #D4AF37;
	color: white;
	border: none;
	border-radius: 50rpx;
	padding: 20rpx 40rpx;
	font-size: 28rpx;
	font-weight: bold;
}

.add-cart-btn:disabled {
	background-color: #CCCCCC;
}
</style>
